package com.okcl.security;

import com.okcl.entity.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 封装用户信息
 */
@Data
public class LoginUserDetails implements UserDetails {
    List<String> roleNames;
    List<String> permissionNames;
    private User user;

    public LoginUserDetails(User user) {
        this.user = user;
    }

    public LoginUserDetails(User user, List<String> roleNames, List<String> permissionNames) {
        this.user = user;
        this.roleNames = roleNames;
        this.permissionNames = permissionNames;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        /**
         * 当前用户的权限信息
         * 1.角色表权限
         * 2.权限表信息
         */
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (!CollectionUtils.isEmpty(roleNames)) {
            for (String roleName : roleNames) {
                roleName = "ROLE_" + roleName;
                grantedAuthorities.add(new SimpleGrantedAuthority(roleName));
            }
        }
        if (!CollectionUtils.isEmpty(permissionNames)) {
            for (String permissionName : permissionNames) {
                grantedAuthorities.add(new SimpleGrantedAuthority(permissionName));
            }
        }
        return grantedAuthorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
